package com.sciencep.pro.admin.system.common.authentication;


import com.alibaba.fastjson.JSON;
import com.sciencep.pro.common.utils.HttpContextUtil;
import com.sciencep.pro.core.domain.dto.user.UserDetail;
import com.sciencep.pro.core.service.RedisService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

import static com.sciencep.pro.admin.system.common.authentication.JWTFilter.TOKEN;
import static com.sciencep.pro.common.config.Constant.USERINFO_CACHE_PREFIX;

/**
 * 自定义实现 ShiroRealm，包含认证和授权两大模块
 *
 * @author Sciencep
 */
@Slf4j
public class ShiroRealm extends AuthorizingRealm  {

    @Autowired
    private RedisService redisService;


    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * `
     * 授权模块，获取用户角色和权限
     *
     * @param token token
     * @return AuthorizationInfo 权限信息
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection token) {



        return new SimpleAuthorizationInfo();
    }

    /**
     * 用户认证
     *
     * @param authenticationToken 身份认证 token
     * @return AuthenticationInfo 身份认证信息
     * @throws AuthenticationException 认证相关异常
     */
    @SneakyThrows
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) {
        String loginErrorMessage = "login_error_message";
        // 这里的 token是从 JWTFilter 的 executeLogin 方法传递过来的，已经经过了解密
        HttpServletRequest request = HttpContextUtil.getHttpServletRequest();
        String token = request.getHeader(TOKEN);
        String userId = JWTUtil.getUserId(token);
        String value;
        try {
            value = redisService.get(USERINFO_CACHE_PREFIX + userId);
        } catch (Exception e) {
            log.error("redis错误{}", e.getMessage());
            request.setAttribute(loginErrorMessage,"redis连接失败");
            throw new AuthenticationException("redis连接失败");
        }
        UserDetail userDetail = JSON.parseObject(value, UserDetail.class);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        Date expireTime =  simpleDateFormat.parse(userDetail.getExpireTimeStr());
        String currentTimeStr =  simpleDateFormat.format(new Date());
        Date currentTime = simpleDateFormat.parse(currentTimeStr);
        if (expireTime.compareTo(currentTime) < 0) {
            request.setAttribute(loginErrorMessage,"token已经过期,请重新登录");
            throw new AuthenticationException("token已经过期,请重新登录");
        }
        if (!token.equals(userDetail.getToken())) {
            request.setAttribute(loginErrorMessage,"该账号已在其它地方登录 请重新登录");
            throw new AuthenticationException("该账号已在其它地方登录 请重新登录");
        }
        if (!JWTUtil.verify(token,userDetail.getUserId())) {
            throw new AuthenticationException("token校验不通过");
        }
        // 通过用户名查询用户信息
        return new SimpleAuthenticationInfo(token, token, "osca_shiro_realm");
    }
}
